from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from .core.config import settings

# 数据库URL是根据从环境变量加载的设置构建的。
# 格式为: "mysql+pymysql://user:password@host/dbname"
DATABASE_URL = (
    f"mysql+pymysql://{settings.database_username}:{settings.database_password}@"
    f"{settings.database_hostname}/{settings.database_name}"
)

engine = create_engine(DATABASE_URL, pool_pre_ping=True)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

def get_db():
    """
    用于获取数据库会话的FastAPI依赖项。
    确保在请求之后总是关闭会话。
    """
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close() 